/* eslint-disable react/jsx-no-comment-textnodes */
"use client";
import React, { use } from "react";
import type { UserCenterGetProductResponses } from "@/apis";
import { Skeleton, Alert, Empty, Breadcrumb, message, Modal } from "antd";
import { authFetch } from "@/utils/auth";
import {
  HomeOutlined,
  AppstoreOutlined,
  BookOutlined,
  SearchOutlined,
  ShareAltOutlined,
  HeartOutlined,
} from "@ant-design/icons";
import Image from "next/image";
import Link from "next/link";

// 类型定义
interface ProductDetailPageProps {
  params: Promise<{
    id: string;
  }>;
}

type CenterProductDetailModel = NonNullable<
  UserCenterGetProductResponses["200"]["data"]
>;

// 工具函数：处理图片URL
const getFullImageUrl = (relativePath?: string) => {
  if (!relativePath) return "/images/default-product.png";
  if (relativePath.startsWith("http")) return relativePath;
  const ossBaseUrl = "https://oss.tz-group.com/";
  const cleanPath = relativePath.startsWith("/")
    ? relativePath.slice(1)
    : relativePath;
  return `${ossBaseUrl}${cleanPath}`;
};

// 工具函数：映射检测状态
// const mapInspectionStatus = (status?: number) => {
//   switch (status) {
//     case 0:
//       return "检测中";
//     case 1:
//       return "检测完成";
//     default:
//       return "未知状态";
//   }
// };

// 工具函数：映射规格型号类型
// const mapModelType = (type?: number) => {
//   switch (type) {
//     case 0:
//       return "产地";
//     case 1:
//       return "特点";
//     default:
//       return "未定义";
//   }
// };

export default function ProductDetailPage({ params }: ProductDetailPageProps) {
  const { id } = use(params);
  const productId = Number(id);
  const [productDetail, setProductDetail] =
    React.useState<CenterProductDetailModel | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [errorMsg, setErrorMsg] = React.useState<string | null>(null);
  const [inspectionModalVisible, setInspectionModalVisible] =
    React.useState(false);
  const [isFavorite, setIsFavorite] = React.useState(false);
  const [favoriteLoading, setFavoriteLoading] = React.useState(false);
  const [wechatCode, setWechatCode] = React.useState<string | null>(null);
  const [codeLoading, setCodeLoading] = React.useState(false);
  const [shareModalVisible, setShareModalVisible] = React.useState(false);

  // 获取微信小程序码
  const fetchWechatCode = React.useCallback(async () => {
    try {
      setCodeLoading(true);
      console.log("开始获取小程序码，产品ID:", productId);

      const response = await authFetch(`/api/wechat?id=${productId}`, {
        method: "POST",
      });

      console.log("API响应状态:", response.status);

      const data = (await response.json()) as {
        success: boolean;
        data?: { codeAddress?: string };
        message?: string;
      };
      console.log("API响应数据:", data);

      if (data.success && data.data?.codeAddress) {
        setWechatCode(data.data.codeAddress);
        console.log("获取到小程序码:", data.data.codeAddress);
        message.success("小程序码加载成功");
      } else {
        console.error("获取小程序码失败:", data.message || "未知错误");
        message.error(`获取小程序码失败: ${data.message || "未知错误"}`);
      }
    } catch (error: unknown) {
      console.error("获取小程序码出错:", error);
      if (error instanceof Error && error.message === "用户未登录") {
        message.warning("请先登录后再获取小程序码");
      } else {
        message.error("获取小程序码出错");
      }
    } finally {
      setCodeLoading(false);
    }
  }, [productId]);

  // 处理科普点击
  const handleScienceClick = () => {
    const targetElement = document.getElementById("inspection-certification");
    if (targetElement) {
      // 获取目标元素的位置
      const targetPosition = targetElement.offsetTop;
      // 添加偏移量，确保标题完全显示（考虑可能的固定头部高度）
      const offset = 80;

      // 平滑滚动到目标位置
      window.scrollTo({
        top: targetPosition - offset,
        behavior: "smooth",
      });

      // 添加高亮效果
      targetElement.style.transition = "background-color 0.3s ease";
      targetElement.style.backgroundColor = "#f0f9ff";

      // 2秒后移除高亮效果
      setTimeout(() => {
        targetElement.style.backgroundColor = "";
      }, 2000);
    }
  };

  // 处理溯源点击 - 直接使用检测溯源详情
  const handleTraceClick = () => {
    handleInspectionDetailClick();
  };

  // 处理转发点击
  const handleShareClick = () => {
    setShareModalVisible(true);
  };

  // 处理分享弹窗关闭
  const handleShareModalClose = () => {
    setShareModalVisible(false);
  };

  // 处理下载图片
  const handleDownloadImage = () => {
    if (!productDetail) return;

    // 创建画布
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    // 设置画布尺寸
    canvas.width = 400;
    canvas.height = 600;

    // 背景色
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 标题
    ctx.fillStyle = "#333333";
    ctx.font = "bold 20px Arial";
    ctx.textAlign = "center";
    ctx.fillText("产品分享", canvas.width / 2, 40);

    // 产品名称
    ctx.font = "16px Arial";
    ctx.fillText(
      productDetail.productName || "未命名产品",
      canvas.width / 2,
      80
    );

    // 等级信息 - 绘制标准菱形边框
    const gradeName = productDetail.identityData?.gradeName || "等级认证";
    const gradeColors: Record<string, string> = {
      A: "#027F3F",
      B: "#68D300",
      C: "#FFB422",
      D: "#FF8738",
    };

    // 绘制平行四边形
    const parallelogramWidth = 200;
    const parallelogramHeight = 80;
    const parallelogramX = (canvas.width - parallelogramWidth) / 2;
    const parallelogramY = 90;
    const skewOffset = 40; // 平行四边形的倾斜偏移

    ctx.save();

    // 绘制右倾斜平行四边形背景（带圆角）
    const cornerRadius = 8; // 圆角半径
    ctx.fillStyle = "#f0f9ff";
    ctx.beginPath();

    // 左上角圆角
    ctx.moveTo(parallelogramX + cornerRadius, parallelogramY);
    ctx.lineTo(
      parallelogramX + parallelogramWidth - cornerRadius,
      parallelogramY
    );
    ctx.quadraticCurveTo(
      parallelogramX + parallelogramWidth,
      parallelogramY,
      parallelogramX + parallelogramWidth,
      parallelogramY + cornerRadius
    );

    // 右上角到右下角
    ctx.lineTo(
      parallelogramX + parallelogramWidth - skewOffset - cornerRadius,
      parallelogramY + parallelogramHeight - cornerRadius
    );
    ctx.quadraticCurveTo(
      parallelogramX + parallelogramWidth - skewOffset,
      parallelogramY + parallelogramHeight,
      parallelogramX + parallelogramWidth - skewOffset - cornerRadius,
      parallelogramY + parallelogramHeight
    );

    // 右下角到左下角
    ctx.lineTo(
      parallelogramX - skewOffset + cornerRadius,
      parallelogramY + parallelogramHeight
    );
    ctx.quadraticCurveTo(
      parallelogramX - skewOffset,
      parallelogramY + parallelogramHeight,
      parallelogramX - skewOffset,
      parallelogramY + parallelogramHeight - cornerRadius
    );

    // 左下角到左上角
    ctx.lineTo(parallelogramX + cornerRadius, parallelogramY + cornerRadius);
    ctx.quadraticCurveTo(
      parallelogramX,
      parallelogramY,
      parallelogramX + cornerRadius,
      parallelogramY
    );

    ctx.closePath();
    ctx.fill();

    // 绘制平行四边形边框
    ctx.strokeStyle = "#1677FF";
    ctx.lineWidth = 1;
    ctx.stroke();

    ctx.restore();

    // 在平行四边形内绘制内容
    ctx.fillStyle = "#1677FF";
    ctx.font = "bold 16px Arial";
    ctx.textAlign = "center";
    ctx.fillText(gradeName, canvas.width / 2, 115);

    ctx.fillStyle = "#666666";
    ctx.font = "12px Arial";
    ctx.fillText("质量等级", canvas.width / 2, 130);

    // 绘制ABCD等级
    const gradeLabels = ["A", "B", "C", "D"];
    const startX = canvas.width / 2 - 60;
    gradeLabels.forEach((label, index) => {
      const x = startX + index * 30;
      const y = 150;

      // 等级标签背景
      ctx.fillStyle = gradeColors[label] || "#027F3F";
      ctx.fillRect(x - 10, y - 10, 20, 20);

      // 等级标签文字
      ctx.fillStyle = "#ffffff";
      ctx.font = "bold 12px Arial";
      ctx.textAlign = "center";
      ctx.fillText(label, x, y + 4);
    });

    // 二维码和平台信息区域 - 统一背景
    const sectionY = 180;
    const sectionHeight = 120;
    const sectionWidth = 350;
    const sectionX = (canvas.width - sectionWidth) / 2;

    // 绘制渐变背景
    const gradient = ctx.createLinearGradient(
      0,
      sectionY,
      0,
      sectionY + sectionHeight
    );
    gradient.addColorStop(0, "#dbeafe"); // blue-100
    gradient.addColorStop(0.5, "#e0e7ff"); // indigo-100
    gradient.addColorStop(1, "#f3e8ff"); // purple-100

    ctx.fillStyle = gradient;
    ctx.fillRect(sectionX, sectionY, sectionWidth, sectionHeight);

    // 绘制二维码背景
    const qrY = sectionY + 20;
    const qrSize = 80;
    const qrX = (canvas.width - qrSize) / 2;

    ctx.fillStyle = "#ffffff";
    ctx.fillRect(qrX, qrY, qrSize, qrSize);

    // 绘制平台信息背景
    const platformY = qrY + qrSize + 20;
    const platformHeight = 30;
    const platformWidth = 250;
    const platformX = (canvas.width - platformWidth) / 2;

    ctx.fillStyle = "#ffffff";
    ctx.fillRect(platformX, platformY, platformWidth, platformHeight);

    // 绘制平台信息文字
    ctx.fillStyle = "#374151";
    ctx.font = "bold 14px Arial";
    ctx.textAlign = "center";
    ctx.fillText("国家工信部", canvas.width / 2, platformY + 15);

    ctx.fillStyle = "#6b7280";
    ctx.font = "10px Arial";
    ctx.fillText(
      "中小企业数字化转型示范平台",
      canvas.width / 2,
      platformY + 25
    );

    // 转换为图片并下载
    canvas.toBlob((blob) => {
      if (blob) {
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `${productDetail.productName || "产品"}_分享图.png`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        message.success("图片下载成功");
      }
    }, "image/png");
  };

  // 处理收藏点击
  const handleFavoriteClick = async () => {
    setFavoriteLoading(true);

    // 直接检查 localStorage
    const userInfo = localStorage.getItem("userInfo");
    const token = localStorage.getItem("token");

    console.log("Frontend - userInfo:", userInfo);
    console.log("Frontend - token:", token);
    console.log("Frontend - token length:", token?.length);

    if (!userInfo || !token) {
      message.warning("请先登录后再收藏");
      setFavoriteLoading(false);
      return;
    }

    // 解析用户信息，获取JWT token
    const userInfoObj = JSON.parse(userInfo);
    const jwtToken = userInfoObj?.token; // 这个应该是JWT格式的token

    console.log("Frontend - userInfoObj:", userInfoObj);
    console.log("Frontend - jwtToken:", jwtToken);
    console.log("Frontend - jwtToken type:", typeof jwtToken);
    console.log("Frontend - jwtToken length:", jwtToken?.length);
    console.log(
      "Frontend - jwtToken starts with eyJ:",
      jwtToken?.startsWith("eyJ")
    );

    if (!jwtToken) {
      message.warning("登录信息无效，请重新登录");
      setFavoriteLoading(false);
      return;
    }

    if (!productDetail) {
      message.error("产品信息加载中，请稍后再试");
      setFavoriteLoading(false);
      return;
    }

    try {
      if (isFavorite) {
        // 取消收藏
        const response = await authFetch(
          `/api/favorite/remove?productId=${productId}`,
          {
            method: "POST",
          }
        );

        if (!response.ok) {
          const errorData = await response.json();
          console.log("取消收藏API错误响应:", errorData);
          // 临时禁用自动跳转，先看调试信息
          // if (errorData.code === "TOKEN_EXPIRED") {
          //   localStorage.removeItem("userInfo");
          //   localStorage.removeItem("token");
          //   message.error("登录信息已过期，请重新登录");
          //   window.location.href = "/login";
          //   return;
          // }
          throw new Error(
            `HTTP ${response.status}: ${errorData.error || "Unknown error"}`
          );
        }

        setIsFavorite(false);
        message.success("已取消收藏");
      } else {
        // 添加收藏
        const response = await authFetch(
          `/api/favorite?productId=${productId}`,
          {
            method: "POST",
          }
        );

        if (!response.ok) {
          const errorData = await response.json();
          console.log("收藏API错误响应:", errorData);
          // 临时禁用自动跳转，先看调试信息
          // if (errorData.code === "TOKEN_EXPIRED") {
          //   localStorage.removeItem("userInfo");
          //   localStorage.removeItem("token");
          //   message.error("登录信息已过期，请重新登录");
          //   window.location.href = "/login";
          //   return;
          // }
          throw new Error(
            `HTTP ${response.status}: ${errorData.error || "Unknown error"}`
          );
        }

        setIsFavorite(true);
        message.success("收藏成功");
      }
    } catch (error) {
      console.error("收藏操作失败:", error);
      message.error(isFavorite ? "取消收藏失败" : "收藏失败");
    } finally {
      setFavoriteLoading(false);
    }
  };

  // 处理购买直达点击
  const handleDirectPurchaseClick = () => {
    if (!productDetail?.directLink) {
      message.warning("暂无购买链接");
      return;
    }

    const directType = productDetail.directType;
    const directLink = productDetail.directLink;

    if (directType === 0) {
      // 网址类型，直接跳转
      window.open(directLink, "_blank", "noopener,noreferrer");
    } else if (directType === 1) {
      // 手机号类型，复制到剪贴板
      navigator.clipboard
        .writeText(directLink)
        .then(() => {
          message.success(`手机号 ${directLink} 已复制到剪贴板`);
        })
        .catch(() => {
          message.error("复制失败，请手动复制");
        });
    } else {
      message.warning("未知的直达类型");
    }
  };

  // 处理检测溯源详情弹窗
  const handleInspectionDetailClick = () => {
    setInspectionModalVisible(true);
  };

  const handleInspectionModalClose = () => {
    setInspectionModalVisible(false);
  };

  // 获取产品详情数据
  React.useEffect(() => {
    // 临时替换为原生 fetch 测试
    const fetchProductDetail = async () => {
      try {
        setLoading(true);
        const fullUrl = `/api/proxy/user_center/product/detail?productId=${productId}`;

        const response = await fetch(fullUrl);
        if (!response.ok) throw new Error(`HTTP ${response.status}`);

        const data = await response.json();
        if (data.success && data.data) {
          setProductDetail(data.data);
          // 初始化收藏状态
          setIsFavorite(data.data.isFavorite || false);
          // 获取微信小程序码
          fetchWechatCode();
        } else {
          setErrorMsg(data.message || "获取失败");
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
      } catch (err) {
        setErrorMsg("请求失败");
      } finally {
        setLoading(false);
      }
    };

    fetchProductDetail();
  }, [productId, fetchWechatCode]);

  // 加载中状态
  if (loading) {
    return (
      <div className="min-h-screen bg-[url('/images/productBg.png')] bg-no-repeat bg-cover bg-fixed">
        <div className="container mx-auto p-4 mt-6">
          <Skeleton
            active
            title={{ width: "40%" }}
            paragraph={{ rows: 15, width: "100%" }}
          />
        </div>
      </div>
    );
  }

  // 错误状态
  if (errorMsg) {
    return (
      <div className="min-h-screen bg-[url('/images/productBg.png')] bg-no-repeat bg-cover bg-fixed">
        <div className="container mx-auto p-4 mt-8">
          <Alert
            message="请求失败"
            description={errorMsg}
            type="error"
            showIcon
            className="bg-white p-4 rounded-lg"
          />
        </div>
      </div>
    );
  }

  // 无数据状态
  if (!productDetail) {
    return (
      <div className="min-h-screen bg-[url('/images/productBg.png')] bg-no-repeat bg-cover bg-fixed">
        <div className="container mx-auto p-4 mt-8">
          <Empty description="未找到该产品信息" />
        </div>
      </div>
    );
  }

  // 成功状态 - 渲染产品详情
  return (
    <div className="min-h-screen bg-[url('/images/productBg.png')] bg-no-repeat bg-cover bg-fixed">
      {/* 面包屑导航 */}
      <div>
        <div className="container mx-auto px-4 py-3">
          <Breadcrumb
            items={[
              {
                title: (
                  <Link href="/" className="flex items-center">
                    <HomeOutlined className="mr-1" />
                    首页
                  </Link>
                ),
              },
              {
                title: (
                  <Link href="/products" className="flex items-center">
                    <AppstoreOutlined className="mr-1" />
                    产品列表
                  </Link>
                ),
              },
              {
                title: productDetail.productName || "产品详情",
              },
            ]}
          />
        </div>
      </div>

      {/* 产品标题区域 - 跟随滚动 */}
      <div id="inspection-certification" className="backdrop-blur-sm">
        <div className="container mx-auto px-4 py-4">
          <h1 className="text-2xl font-bold text-[#061047] flex items-center justify-center">
            <Image
              src="/images/productTitleIcon.png"
              alt="标题图标"
              width={24}
              height={24}
              className="mr-2"
              style={{ width: "auto", height: "auto" }}
            />
            检测认证 - 公示详情
            <Image
              src="/images/productTitleIcon.png"
              alt="标题图标"
              width={24}
              height={24}
              className="ml-2 scale-x-[-1]"
              style={{ width: "auto", height: "auto" }}
            />
          </h1>
          {/* 副标题 */}
          <h4 className="text-lg font-medium text-[#061047] flex items-center justify-center">
            检测，彰显真实品质
          </h4>
        </div>
      </div>

      {/* 主要内容区域 - 左右分栏布局 */}
      <div className="container mx-auto px-4 py-6">
        <div className="flex gap-6">
          {/* 左侧固定区域 */}
          <div className="w-[28rem] bg-white rounded-lg shadow-sm sticky top-4 h-fit">
            {/* 产品主图 */}
            <div className="p-4">
              {productDetail.mainPhotoes &&
              productDetail.mainPhotoes.length > 0 ? (
                <div className="relative w-full aspect-square mb-4">
                  <Image
                    src={getFullImageUrl(
                      productDetail.mainPhotoes[0].attachmentAddress
                    )}
                    alt={
                      productDetail.mainPhotoes[0].attachmentName ||
                      productDetail.productName ||
                      "产品主图"
                    }
                    fill
                    className="object-contain rounded"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src =
                        "/images/default-product.png";
                    }}
                  />
                </div>
              ) : (
                <div className="w-full aspect-square bg-gray-100 rounded flex items-center justify-center mb-4">
                  <span className="text-gray-400">暂无图片</span>
                </div>
              )}
            </div>

            {/* 产品信息 */}
            <div className="px-4 pb-4">
              <div className="flex gap-4">
                {/* 左侧文字信息 */}
                <div className="flex-1">
                  {/* 产品名称 */}
                  <h2 className="text-lg font-semibold text-[#333] mb-4">
                    {productDetail.productName || "未命名产品"}
                  </h2>

                  {/* 品牌 */}
                  <div className="mb-4">
                    <span className="text-sm text-gray-600">品牌：</span>
                    <span className="text-sm text-[#333]">
                      {productDetail.brand || "无"}
                    </span>
                  </div>

                  {/* 规格型号 */}
                  <div className="mb-4">
                    <span className="text-sm text-gray-600">规格：</span>
                    <span className="text-sm text-[#333]">
                      {productDetail.model || "无"}
                    </span>
                  </div>

                  {/* Tag标签 */}
                  <div className="mb-4">
                    <div className="flex flex-wrap gap-2 mt-1">
                      {productDetail.identityData?.gradeName && (
                        <span className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded">
                          {productDetail.identityData.gradeName}
                        </span>
                      )}
                    </div>
                  </div>

                  {/* 防护等级 ABCD */}
                  <div className="mb-4">
                    <div className="flex space-x-2 mt-3">
                      {[
                        { grade: "A", label: "A", color: "#027F3F" },
                        { grade: "B", label: "B", color: "#68D300" },
                        { grade: "C", label: "C", color: "#FFB422" },
                        { grade: "D", label: "D", color: "#FF8738" },
                      ].map((gradeInfo) => {
                        const currentGrade =
                          productDetail.identityData?.grade || "A";
                        return (
                          <span
                            key={gradeInfo.grade}
                            className={`px-3 py-1 text-white rounded transform skew-x-22 text-lg font-medium transition-all duration-200 ${
                              currentGrade === gradeInfo.grade
                                ? "h-8 scale-110 shadow-md"
                                : "h-6 opacity-80"
                            }`}
                            style={{
                              backgroundColor: gradeInfo.color,
                              lineHeight:
                                currentGrade === gradeInfo.grade
                                  ? "24px"
                                  : "18px",
                            }}
                          >
                            <span className="transform -skew-x-22 inline-block">
                              {gradeInfo.label}
                            </span>
                          </span>
                        );
                      })}
                    </div>
                  </div>

                  {/* 数据来源 */}
                  <div className="mb-6">
                    <span className="text-sm text-gray-600">数据来源：</span>
                    <span className="text-sm text-[#333]">
                      {productDetail.inspectionData?.inspectionOrganization ||
                        "未知"}
                    </span>
                  </div>
                </div>

                {/* 右侧二维码区域 */}
                <div className="w-46 h-46 relative">
                  <div
                    className="w-full h-full bg-cover bg-center bg-no-repeat rounded"
                    style={{
                      backgroundImage: `url('/images/bg_code.png')`,
                    }}
                  >
                    {/* 微信小程序码 */}
                    {codeLoading ? (
                      <div className="w-full h-full flex items-center justify-center p-2">
                        <div className="text-center">
                          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-2"></div>
                          <div className="text-xs text-gray-500">加载中...</div>
                        </div>
                      </div>
                    ) : wechatCode ? (
                      <div className="w-full h-full flex items-center justify-center p-2">
                        <Image
                          src={wechatCode}
                          alt="微信小程序码"
                          width={110}
                          height={110}
                          className="object-contain"
                          onError={(e) => {
                            console.error("小程序码加载失败:", wechatCode);
                            (e.target as HTMLImageElement).src =
                              "/images/default-product.png";
                          }}
                          onLoad={() => {
                            console.log("小程序码加载成功:", wechatCode);
                          }}
                        />
                      </div>
                    ) : (
                      <div className="w-full h-full flex items-center justify-center p-2">
                        <div className="text-center text-gray-400">
                          <div className="text-xs">暂无小程序码</div>
                          <button
                            onClick={fetchWechatCode}
                            className="mt-2 text-xs text-blue-500 hover:text-blue-700 underline"
                          >
                            重新获取
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                  {/* 检测溯源详情按钮 */}
                  <button
                    onClick={handleInspectionDetailClick}
                    className="text-white px-4 py-2 absolute -bottom-14 left-1/2 transform -translate-x-1/2 bg-blue-500  rounded-lg text-sm font-medium hover:bg-blue-600 transition-colors shadow-lg hover:shadow-xl"
                  >
                    一键溯源
                  </button>
                </div>
              </div>

              {/* 功能图标按钮 */}
              <div className="grid grid-cols-4 gap-2 mb-3">
                <button
                  onClick={handleScienceClick}
                  className="flex flex-col items-center justify-center p-3 bg-gray-50 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <BookOutlined className="text-lg text-gray-600 mb-1" />
                  <span className="text-xs text-gray-600">科普</span>
                </button>
                <button
                  onClick={handleTraceClick}
                  className="flex flex-col items-center justify-center p-3 bg-gray-50 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <SearchOutlined className="text-lg text-gray-600 mb-1" />
                  <span className="text-xs text-gray-600">溯源</span>
                </button>
                <button
                  onClick={handleShareClick}
                  className="flex flex-col items-center justify-center p-3 bg-gray-50 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <ShareAltOutlined className="text-lg text-gray-600 mb-1" />
                  <span className="text-xs text-gray-600">转发</span>
                </button>
                <button
                  onClick={handleFavoriteClick}
                  disabled={favoriteLoading}
                  className={`flex flex-col items-center justify-center p-3 rounded-lg transition-colors ${
                    isFavorite
                      ? "bg-yellow-50 hover:bg-yellow-100 text-yellow-600"
                      : "bg-gray-50 hover:bg-gray-100 text-gray-600"
                  } ${favoriteLoading ? "opacity-50 cursor-not-allowed" : ""}`}
                >
                  <HeartOutlined
                    className={`text-lg mb-1 ${
                      isFavorite ? "text-yellow-500" : "text-gray-600"
                    }`}
                    style={{ fill: isFavorite ? "#eab308" : "none" }}
                  />
                  <span className="text-xs">
                    {favoriteLoading
                      ? "处理中..."
                      : isFavorite
                      ? "已收藏"
                      : "收藏"}
                  </span>
                </button>
              </div>

              {/* 操作按钮 */}
              <div className="space-y-3">
                {productDetail.directLink ? (
                  <button
                    onClick={handleDirectPurchaseClick}
                    className="w-full bg-gradient-to-r from-pink-500 via-purple-500 to-indigo-500 text-white py-4 px-6 rounded-xl hover:from-pink-600 hover:via-purple-600 hover:to-indigo-600 transition-all duration-300 font-bold text-lg shadow-2xl hover:shadow-pink-500/25 hover:scale-105 transform hover:-translate-y-1 relative overflow-hidden group"
                  >
                    <span className="relative z-10 flex items-center justify-center text-white">
                      <span className="mr-2">🛒</span>
                      {productDetail.directType === 0 ? "购买直达" : "联系购买"}
                      <span className="ml-2">✨</span>
                    </span>
                    <div className="absolute inset-0 bg-gradient-to-r from-yellow-400 via-pink-400 to-purple-400 opacity-0 group-hover:opacity-20 transition-opacity duration-300"></div>
                  </button>
                ) : (
                  <button
                    disabled
                    className="w-full bg-gray-300 text-gray-500 py-3 text-white  px-4 rounded-lg cursor-not-allowed font-medium"
                  >
                    暂无购买链接
                  </button>
                )}
              </div>
            </div>
          </div>

          {/* 右侧内容区域 - 自然高度 */}
          <div
            id="main-content"
            className="flex-1 bg-white rounded-lg shadow-sm p-6"
          >
            {/* 1. 指标科普 */}
            <div id="target-science" className="mb-8">
              <h2 className="text-lg font-semibold text-[#333] mb-4 flex items-center">
                <span className="font-bold text-2xl text-[#2174C2] mr-2">
                  //
                </span>{" "}
                指标科普
              </h2>

              {productDetail.targetScienceData?.attachments &&
              productDetail.targetScienceData.attachments.length > 0 ? (
                <div className="space-y-4">
                  {productDetail.targetScienceData.attachments.map(
                    (attach, idx: number) => (
                      <div key={idx}>
                        <Image
                          src={getFullImageUrl(attach.attachmentAddress)}
                          alt={attach.attachmentName || `科普资料${idx + 1}`}
                          width={1200}
                          height={800}
                          sizes="100vw"
                          className="w-4/6 h-auto object-contain mx-auto "
                          onError={(e) => {
                            (e.target as HTMLImageElement).src =
                              "/images/default-product.png";
                          }}
                        />
                      </div>
                    )
                  )}
                </div>
              ) : (
                <div className="w-full h-48 bg-gray-100  flex items-center justify-center">
                  <span className="text-gray-400">暂无指标科普内容</span>
                </div>
              )}
            </div>

            {/* 2. 科普视频 */}
            <div className="border-t pt-6 mb-8">
              <h2 className="text-lg font-semibold text-[#333] mb-4 flex items-center">
                <span className="font-bold text-2xl text-[#2174C2] mr-2">
                  //
                </span>
                科普视频
              </h2>
              {productDetail.scienceVideoData ? (
                <div className="space-y-4">
                  {/* 科普视频封面 */}
                  {productDetail.scienceVideoData.covers &&
                    productDetail.scienceVideoData.covers.length > 0 && (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {productDetail.scienceVideoData.covers.map(
                          (cover, idx: number) => (
                            <div key={idx} className="relative">
                              <Image
                                src={getFullImageUrl(cover.attachmentAddress)}
                                alt={cover.attachmentName || "科普视频封面"}
                                width={1200}
                                height={800}
                                sizes="(max-width: 768px) 100vw, 50vw"
                                className="w-full h-48 object-cover rounded-lg"
                                onError={(e) => {
                                  (e.target as HTMLImageElement).src =
                                    "/images/default-product.png";
                                }}
                              />
                            </div>
                          )
                        )}
                      </div>
                    )}

                  {/* 科普视频附件 */}
                  {productDetail.scienceVideoData.attachments &&
                    productDetail.scienceVideoData.attachments.length > 0 && (
                      <div className="space-y-2">
                        <h4 className="text-md font-medium text-[#666]">
                          视频附件
                        </h4>
                        <div className="w-full relative">
                          {/* 左侧装饰图片 */}
                          <div className="absolute left-0 top-1/2 transform -translate-y-1/2 -translate-x-4 z-10">
                            <Image
                              src="/images/shu.png"
                              alt="左侧装饰"
                              width={60}
                              height={60}
                              className="opacity-80"
                            />
                          </div>

                          {/* 右侧装饰图片 */}
                          <div className="absolute right-0 top-1/2 transform -translate-y-1/2 translate-x-4 z-10">
                            <Image
                              src="/images/shu.png"
                              alt="右侧装饰"
                              width={60}
                              height={60}
                              className="opacity-80"
                            />
                          </div>

                          {productDetail.scienceVideoData.attachments.map(
                            (attachment, idx: number) => {
                              // 检查是否为视频文件
                              const isVideo = attachment.attachmentAddress
                                ?.toLowerCase()
                                ?.match(/\.(mp4|webm|ogg|mov|avi|mkv)$/);

                              if (isVideo) {
                                // 如果是视频文件，显示视频播放器
                                return (
                                  <div key={idx} className="relative">
                                    <video
                                      controls
                                      className="w-full h-200 object-cover rounded-lg"
                                    >
                                      <source
                                        src={getFullImageUrl(
                                          attachment.attachmentAddress || ""
                                        )}
                                        type="video/mp4"
                                      />
                                      您的浏览器不支持视频播放。
                                    </video>
                                  </div>
                                );
                              } else {
                                // 如果是图片文件，显示图片
                                return (
                                  <div key={idx} className="relative">
                                    <Image
                                      src={getFullImageUrl(
                                        attachment.attachmentAddress || ""
                                      )}
                                      alt={
                                        attachment.attachmentName || "科普图片"
                                      }
                                      width={1200}
                                      height={800}
                                      sizes="(max-width: 768px) 100vw, 50vw"
                                      className="w-full h-200 object-cover rounded-lg"
                                      onError={(e) => {
                                        (e.target as HTMLImageElement).src =
                                          "/images/default-product.png";
                                      }}
                                    />
                                  </div>
                                );
                              }
                            }
                          )}
                        </div>
                      </div>
                    )}
                </div>
              ) : (
                <div className="w-full h-48 bg-gray-100 rounded-lg flex items-center justify-center">
                  <span className="text-gray-400">暂无科普视频内容</span>
                </div>
              )}
            </div>

            {/* 3. 商品详情 */}
            <div className="border-t pt-6 mb-8">
              <h2 className="text-lg font-semibold text-[#333] mb-4 flex items-center">
                <span className="font-bold text-2xl text-[#2174C2] mr-2">
                  //
                </span>
                商品详情
              </h2>

              {/* 商品详情图片 */}
              {productDetail.productData?.introductionPhotoes &&
              productDetail.productData.introductionPhotoes.length > 0 ? (
                <div className="mb-6">
                  <div className="grid grid-cols-1 gap-4">
                    {productDetail.productData.introductionPhotoes.map(
                      (photo, idx: number) => (
                        <div key={idx} className="relative">
                          <Image
                            src={getFullImageUrl(photo.attachmentAddress)}
                            alt={photo.attachmentName || "产品介绍图"}
                            width={1200}
                            height={800}
                            sizes="(max-width: 768px) 100vw, 80vw"
                            className="w-4/6 h-auto object-contain mx-auto rounded-lg shadow-sm"
                            onError={(e) => {
                              (e.target as HTMLImageElement).src =
                                "/images/default-product.png";
                            }}
                          />
                        </div>
                      )
                    )}
                  </div>
                </div>
              ) : null}
            </div>
          </div>
        </div>
      </div>

      {/* 检测溯源详情弹窗 */}
      <Modal
        title={
          <div
            className="font-semibold text-lg py-2 px-14 rounded-t-lg"
            style={{
              backgroundImage: "url('/images/detailTitle.png')",
              backgroundSize: "contain",
              backgroundPosition: "left",
              backgroundRepeat: "no-repeat",
            }}
          >
            检测溯源详情
          </div>
        }
        open={inspectionModalVisible}
        onCancel={handleInspectionModalClose}
        footer={null}
        width={800}
        centered
      >
        {productDetail?.inspectionData ? (
          <div className="space-y-6">
            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 bg-gray-50 rounded-lg">
                <h4 className="font-semibold text-gray-700 mb-2">检测机构</h4>
                <p className="text-gray-600">
                  {productDetail.inspectionData.inspectionOrganization ||
                    "未知"}
                </p>
              </div>
              <div className="p-4 bg-gray-50 rounded-lg">
                <h4 className="font-semibold text-gray-700 mb-2">检测时间</h4>
                <p className="text-gray-600">
                  {productDetail.inspectionData.inspectionTime || "无"}
                </p>
              </div>
              <div className="p-4 bg-gray-50 rounded-lg">
                <h4 className="font-semibold text-gray-700 mb-2">检测地点</h4>
                <p className="text-gray-600">
                  {productDetail.inspectionData.inspectionAddress || "未知"}
                </p>
              </div>
              <div className="p-4 bg-gray-50 rounded-lg">
                <h4 className="font-semibold text-gray-700 mb-2">检测设备</h4>
                <p className="text-gray-600">
                  {productDetail.inspectionData.inspectionDevice || "无"}
                </p>
              </div>
            </div>

            {/* 标准信息 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold text-gray-800">标准信息</h3>
              <div className="grid grid-cols-2 gap-4">
                <div className="p-4 bg-blue-50 rounded-lg">
                  <h4 className="font-semibold text-blue-700 mb-2">国标</h4>
                  <p className="text-blue-600">
                    {productDetail.inspectionData.gb || "无"}
                  </p>
                </div>
                <div className="p-4 bg-green-50 rounded-lg">
                  <h4 className="font-semibold text-green-700 mb-2">
                    等级标准
                  </h4>
                  <p className="text-green-600">
                    {productDetail.inspectionData.gradeStandard || "无"}
                  </p>
                </div>
              </div>
            </div>

            {/* 等级信息 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold text-gray-800">等级信息</h3>
              <div className="grid grid-cols-2 gap-4">
                <div className="p-4 bg-orange-50 rounded-lg">
                  <h4 className="font-semibold text-orange-700 mb-2">等级</h4>
                  <p className="text-orange-600">
                    {productDetail.inspectionData.grade || "无"}
                  </p>
                </div>
                <div className="p-4 bg-purple-50 rounded-lg">
                  <h4 className="font-semibold text-purple-700 mb-2">
                    等级名称
                  </h4>
                  <p className="text-purple-600">
                    {productDetail.inspectionData.gradeName || "无"}
                  </p>
                </div>
              </div>
            </div>

            {/* 附件信息 */}
            {productDetail.inspectionData.attachments &&
              productDetail.inspectionData.attachments.length > 0 && (
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold text-gray-800">
                    检测附件
                  </h3>
                  <div className="space-y-2">
                    {productDetail.inspectionData.attachments.map(
                      (attach, idx: number) => (
                        <a
                          key={idx}
                          href={getFullImageUrl(attach.attachmentAddress)}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="flex items-center p-3 bg-gray-50 hover:bg-gray-100 rounded-lg transition-colors"
                        >
                          <span className="text-gray-700 flex-1">
                            {attach.attachmentName || `检测附件${idx + 1}`}
                          </span>
                          <svg
                            className="w-4 h-4 text-gray-400"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth="2"
                              d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                            ></path>
                          </svg>
                        </a>
                      )
                    )}
                  </div>
                </div>
              )}
          </div>
        ) : (
          <div className="text-center py-8">
            <Empty description="暂无检测溯源信息" />
          </div>
        )}
      </Modal>

      {/* 分享弹窗 */}
      <Modal
        title=""
        open={shareModalVisible}
        onCancel={handleShareModalClose}
        footer={null}
        width={400}
        centered
        className="share-modal"
        styles={{
          content: {
            background: "transparent",
            boxShadow: "none",
            padding: "10px",
            borderRadius: "12px",
          },
        }}
      >
        <div className="space-y-6 bg-gradient-to-br from-blue-50 to-indigo-100 p-2">
          <div className="bg-white py-8">
            {/* 产品主图 */}
            <div className="w-full">
              {productDetail?.mainPhotoes &&
              productDetail.mainPhotoes.length > 0 ? (
                <div className="relative w-full h-80">
                  <Image
                    src={getFullImageUrl(
                      productDetail.mainPhotoes[0].attachmentAddress
                    )}
                    alt={
                      productDetail.mainPhotoes[0].attachmentName ||
                      productDetail.productName ||
                      "产品主图"
                    }
                    fill
                    className="object-contain"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src =
                        "/images/default-product.png";
                    }}
                  />
                </div>
              ) : (
                <div className="w-full h-80 bg-gray-100 rounded-lg flex items-center justify-center">
                  <span className="text-gray-400">暂无图片</span>
                </div>
              )}
            </div>

            {/* 质量等级区域 - 平行四边形边框包裹 */}
            <div className="flex justify-center">
              <div
                className="relative"
                style={{
                  width: "280px",
                  height: "140px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  position: "relative",
                }}
              >
                <div className="absolute inset-0" />
                {/* 内容区域 */}
                <div className="text-center relative z-10 px-8">
                  <div className="mb-3">
                    <div className="text-lg font-bold text-[#1677FF] mb-1">
                      {productDetail?.identityData?.gradeName || "等级认证"}
                    </div>
                  </div>
                  {/* ABCD 等级 */}
                  <div className="flex justify-center space-x-2">
                    {[
                      { grade: "A", label: "A", color: "#027F3F" },
                      { grade: "B", label: "B", color: "#68D300" },
                      { grade: "C", label: "C", color: "#FFB422" },
                      { grade: "D", label: "D", color: "#FF8738" },
                    ].map((gradeInfo) => {
                      const currentGrade =
                        productDetail?.identityData?.grade || "A";
                      return (
                        <span
                          key={gradeInfo.grade}
                          className={`px-2 py-1 text-white rounded transform skew-x-12 text-sm font-bold transition-all duration-200 ${
                            currentGrade === gradeInfo.grade
                              ? "scale-110 shadow-md"
                              : "opacity-60"
                          }`}
                          style={{
                            backgroundColor: gradeInfo.color,
                          }}
                        >
                          <span className="transform -skew-x-12 inline-block">
                            {gradeInfo.label}
                          </span>
                        </span>
                      );
                    })}
                  </div>
                </div>
              </div>
            </div>

            {/* 二维码和平台信息区域 - 自上而下渐变背景 */}
            <div className="space-y-6 bg-gradient-to-b from-blue-0 to-indigo-100 mx-4">
              <div className="flex justify-center items-center relative">
                <div className="w-48 h-48  flex items-center justify-center">
                  {codeLoading ? (
                    <div className="text-center">
                      <div className="animate-spin h-6 w-6 mx-auto"></div>
                      <div className="text-xs text-gray-500">加载中...</div>
                    </div>
                  ) : wechatCode ? (
                    <Image
                      src={wechatCode}
                      alt="微信小程序码"
                      width={200}
                      height={200}
                      className="object-contain"
                      onError={(e) => {
                        (e.target as HTMLImageElement).src =
                          "/images/default-product.png";
                      }}
                    />
                  ) : (
                    <div className="text-center text-gray-400">
                      <div className="text-xs">暂无小程序码</div>
                    </div>
                  )}
                </div>
              </div>

              {/* 平台信息 */}
              <div className="flex justify-center items-center relative">
                {/* 平台信息容器 */}
                <div className="text-center space-y-1  py-4 px-6">
                  <div className="text-lg font-semibold text-gray-800">
                    国家工信部
                  </div>
                  <div className="text-sm text-gray-600">
                    中小企业数字化转型示范平台
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* 下载按钮 */}
          <div className="flex justify-center">
            <button
              onClick={handleDownloadImage}
              className="bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white px-8 py-3 rounded-lg font-medium transition-all duration-300 shadow-lg hover:shadow-xl transform hover:scale-105"
            >
              📥 下载图片
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
